#!/usr/bin/env python

import gtk
import pygtk
import xmlrpclib

def quit_cb(widget, data = None):
    if data:
        data.set_visible(False)
    gtk.main_quit()

def popup_menu_cb(widget, button, time, data = None):
    if button == 3:
        if data:
            data.show_all()
            data.popup(None, None, None, 3, time)
    pass

def about_box(widget, data = None):
    msgBox = gtk.MessageDialog(parent = None, buttons = gtk.BUTTONS_OK, message_format = "Notebooklet GTK client version 0.10 by Heikki Salo")
    msgBox.run()
    msgBox.destroy()


class SendNoteForm(gtk.Window):

    def __init__(self):
        gtk.Window.__init__(self)
        self.connect('delete_event', self.handle_window_delete_event)
        self.connect('destroy', self.quit)
        self.set_title('Send note')
        self.set_default_size(300, 80)
        vbox = gtk.VBox()
        hboxNote = gtk.HBox()
        hboxControls = gtk.HBox()
        self.entry = gtk.Entry()
        label = gtk.Label('Your note')
        h_adjustment = gtk.Adjustment(value=300, lower=300, upper=600)
        v_adjustment = gtk.Adjustment(value=100, lower=100, upper=400)

        buttoncancel = gtk.Button(stock='gtk-cancel')
        buttoncancel.connect('clicked',self.quit)

        buttonok = gtk.Button(stock='gtk-ok')
        buttonok.connect('clicked',self.send)

        hboxNote.pack_start(label)
        hboxNote.pack_end(self.entry)
        hboxControls.pack_start(buttoncancel)
        hboxControls.pack_end(buttonok)
 
        vbox.pack_start(hboxNote)
        vbox.add(hboxControls)

        self.add(vbox)

    def quit(self, *args):
        self.destroy()
 
    def handle_window_delete_event(self, *args):
        return False
 
    def send(self, *args):
        msgBox = gtk.MessageDialog(parent = None, buttons = gtk.BUTTONS_OK, message_format = "Sending the note!")
        msgBox.run()
        msgBox.destroy()
        server = xmlrpclib.ServerProxy("https://deggis.kapsi.fi/notebooklet/send.php")
        mynote = self.entry.get_text()
        # print "My note was: " + mynote
        response = server.send(mynote)
        msgBox = gtk.MessageDialog(parent = None, buttons = gtk.BUTTONS_OK, message_format = "Server responded: " + response)
        msgBox.run()
        msgBox.destroy()
        self.quit()

def notebooklet_form(widget, data = None):
    main = SendNoteForm()
    main.show_all()
    gtk.main()

statusIcon = gtk.StatusIcon()

menu = gtk.Menu()
menuItem = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
menuItem.connect('activate', about_box)
menu.append(menuItem)
menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
menuItem.connect('activate', quit_cb, statusIcon)
menu.append(menuItem)
 
statusIcon.set_from_stock(gtk.STOCK_HOME)
statusIcon.set_tooltip("Notebooklet")
statusIcon.connect('activate', notebooklet_form)
statusIcon.connect('popup-menu', popup_menu_cb, menu)
statusIcon.set_visible(True)

gtk.main()
